package com.gin.kotlin.no_gay_alliance.fragment.topiclist

import android.content.DialogInterface
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import androidx.core.view.MenuProvider
import com.gin.kotlin.no_gay_alliance.R
import com.gin.kotlin.no_gay_alliance.activity.TopicListActivity.Companion.KEY_ARGUMENT
import com.gin.kotlin.no_gay_alliance.app.App
import com.gin.kotlin.no_gay_alliance.argument.TopicListArgument
import com.gin.kotlin.no_gay_alliance.base.AlertDialogUtils
import com.gin.kotlin.no_gay_alliance.base.InputMethodUtils
import com.gin.kotlin.no_gay_alliance.callback.RCallback
import com.gin.kotlin.no_gay_alliance.databinding.DialogFavorFolderModifyBinding
import com.gin.kotlin.no_gay_alliance.databinding.FragmentTopicListFavorBinding
import com.gin.kotlin.no_gay_alliance.provider.ngaphp.FavorFolderProvider
import com.gin.nga.callback.NgaCallback
import com.gin.nga.enums.FavorFolderType
import com.gin.nga.response.base.NgaResponse
import com.gin.nga.response.favor.FavorFolder
import com.google.android.material.tabs.TabLayout
import retrofit2.Call
import retrofit2.Response

class FavorTopicListFragment : AbstractTopicListFragment<FragmentTopicListFavorBinding>(), MenuProvider, TabLayout.OnTabSelectedListener, RCallback<List<FavorFolder>, Long> {

    private var userId: Long = 0
    private var folder: List<FavorFolder>? = null

    override fun onCreateView() {
        super.onCreateView()
        this.userId = argument.authorUid ?: throw RuntimeException("必须提供用户ID")
        requestFolder(userId)
    }

    override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
        menuInflater.inflate(R.menu.favor_folder, menu)
    }

    override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
        return when (menuItem.itemId) {
            //  修改当前收藏夹
            R.id.mi_edit -> {
                val b = this.b ?: return false
                val folder = folder?.get(b.tabLayout.selectedTabPosition) ?: return false
                Log.d(TAG, "修改收藏夹: ${folder.name}")
                val dialogBinding = DialogFavorFolderModifyBinding.inflate(LayoutInflater.from(requireContext()))
                dialogBinding.editText.setText(folder.name)
                dialogBinding.swIsPublic.isChecked = folder.type == FavorFolderType.PUBLIC
                dialogBinding.editText.requestFocus()
                dialogBinding.editText.selectAll()
                dialogBinding.tvWarningFavorFolder.visibility = if (folder.type == FavorFolderType.DEFAULT) View.VISIBLE else View.GONE

                AlertDialogUtils.builder(requireContext(), contentView = dialogBinding.root, listener = { _, which ->
                    if (which == DialogInterface.BUTTON_POSITIVE) {
                        //发送请求修改
                        App.INSTANCE.ngaApi.favorApi.folderModify(
                            name = dialogBinding.editText.text.toString(),
                            isPublic = if (dialogBinding.swIsPublic.isChecked) 1 else 0,
                            folderId = folder.id!!
                        ).enqueue(object : NgaCallback<List<String>> {
                            override fun onSuccess(
                                call: Call<NgaResponse<List<String>>>,
                                response: Response<NgaResponse<List<String>>>,
                                body: NgaResponse<List<String>>?,
                                data: List<String>?
                            ) {
                                data?.get(0)?.also { toast(it) }
                                requestFolder(userId, true)
                            }

                            override fun onError(
                                call: Call<NgaResponse<List<String>>>,
                                response: Response<NgaResponse<List<String>>>,
                                body: NgaResponse<List<String>>?,
                                errorMessage: String
                            ) {
                                toastLong(errorMessage)
                            }
                        })
                    }
                }).show()

                uiDelayed(500) { InputMethodUtils.show(dialogBinding.editText) }

                true
            }
            // 从收藏夹中移除主题
            R.id.mi_delete -> {
                Log.d(TAG, "删除收藏主题: ")
                currentPageFragment.favorDelete()
                true
            }

            else -> false
        }
    }

    /**
     * 请求收藏夹列表
     * @param userId Long?
     */
    private fun requestFolder(userId: Long, ignoreCache: Boolean = false) {
        b?.tvWarning?.visibility = View.GONE
        FavorFolderProvider.getInstance().enqueue(params = userId, ignoreCache = ignoreCache, callback = this)
    }

    override fun onTabSelected(tab: TabLayout.Tab?) {
        val id = tab?.id ?: return
        val favorFolder = folder?.get(id)
        argument = argument.copy(folderId = favorFolder?.id)
        // 装载适配器
        configViewPager2Adapter()
    }

    override fun onTabUnselected(tab: TabLayout.Tab?) {
    }

    override fun onTabReselected(tab: TabLayout.Tab?) {
    }

    override fun onSuccess(data: List<FavorFolder>, ignoreCache: Boolean) {
        folder = data

        val b = this.b ?: return
        b.tvWarning.visibility = View.GONE
        b.tabLayout.visibility = View.VISIBLE
        b.viewPager2.visibility = View.VISIBLE


        // 根据收藏夹查询结果更正文件夹ID参数
        argument = argument.copy(
            folderId = when (argument.folderId) {
                null -> data.getOrNull(0)?.id
                1L -> data.firstOrNull { it.defaultFolder }?.id
                else -> argument.folderId
            }
        )
        Log.i(TAG, "获得收藏夹: ${data.map { it.name }}")
        if (data.isEmpty()){
            toastLong("未找到收藏夹")
            requireActivity().finish()
            return
        }

        // 根据响应结果配置TabLayout，将收藏夹的下标作为其id
        b.tabLayout.removeAllTabs()
        data.forEach {
            val tab = b.tabLayout.newTab()
            tab.id = data.indexOf(it)
            tab.text = it.getFullName()
            b.tabLayout.addTab(tab)
            // 选中tab
            if (it.id == argument.folderId) b.tabLayout.selectTab(tab)
        }
        // 点击标签后修改参数，重新初始化ViewPager2
        b.tabLayout.addOnTabSelectedListener(this)

        // 装载适配器
        configViewPager2Adapter()
    }

    override fun onError(errorMessage: String) {
        val b = this.b ?: return
        b.tvWarning.text = errorMessage
        b.tvWarning.visibility = View.VISIBLE
        b.tabLayout.visibility = View.GONE
        b.viewPager2.visibility = View.GONE
    }

    companion object {
        fun newInstance(argument: TopicListArgument) = FavorTopicListFragment().also { it.arguments = Bundle().also { b -> b.putParcelable(KEY_ARGUMENT, argument) } }
    }
}